﻿using Nini.Config;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using UltimateMusicTagger;

namespace UltimateMp3TaggerUI
{
    class UMTUtility
    {
        public static IConfigSource GetConfigUI()
        {
            return new IniConfigSource("umtaggerui.ini");
        }

        /// <summary>
        /// GetProxyFromConfig
        /// </summary>
        /// <returns></returns>
        public static WebProxy GetProxyFromConfig()
        {
            WebProxy proxy = null;

            //try
            //{
            IConfigSource configSource = new IniConfigSource("umtagger.ini");

            IConfig configSection = configSource.Configs["Proxy"];

            string enabled = configSection.Get("enable");

            bool isProxyEnabled = false;

            Boolean.TryParse(enabled, out isProxyEnabled);

            if (isProxyEnabled)
            {
                string address = configSection.Get("address");
                int port = int.Parse(configSection.Get("port", "8080"));
                string domain = configSection.Get("domain");
                string username = configSection.Get("user");
                string password = configSection.Get("password");

                if (address != null)
                {
                    if (Uri.IsWellFormedUriString(address, UriKind.RelativeOrAbsolute) == false)
                        address = Dns.GetHostName();

                    proxy = new WebProxy(address, port);
                    NetworkCredential credentials = new NetworkCredential(username, password, domain);
                    proxy.Credentials = credentials;
                }

            }

            return proxy;
        }

        public static string NormalizeFilterPath(string filter)
        {
            string result = null;

            if (String.IsNullOrEmpty(filter) == false)
            {
                string pattern = "[\\.\\*]*";
                string replacement = String.Empty;
                Regex rgx = new Regex(pattern);
                result = rgx.Replace(filter, replacement);
            }

            result = String.IsNullOrEmpty(result) ? "*" : "*." + result;

            return result;
        }

        //public static Version GetProductVersion()
        //{
        //    Assembly assembly = Assembly.GetExecutingAssembly();
        //    FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(Path.GetDirectoryName(assembly.Location) + "/Ultimate Music Tagger.dll");

        //    return new Version(fileVersionInfo.ProductVersion);
        //}

        public static void ShowUpdateSoftwareMessageAsync(bool showMessageAnyway, WebProxy webProxy)
        {

            Task.Factory.StartNew(() => ServiceUpdater.CheckForUpdates(UltimateMusicTagger.Globals.UPDATE_URL, webProxy)).ContinueWith(task =>
            {
                if (task.Result != null)
                {
                    ServiceUpdater.VersionInfo lastVersionInfo = task.Result;

                    Version productVersion = MTUtility.GetVersion();

                    if (lastVersionInfo.LatestVersion > productVersion)
                    {
                        DialogResult result = MessageBox.Show(String.Format("A new version ({0}) is avaible, do you want to go to the homepage?", lastVersionInfo.LatestVersion), "New Version", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);

                        if (result == DialogResult.Yes)
                        {
                            Process.Start(lastVersionInfo.LatestVersionUrl);
                        }
                    }
                    else if (showMessageAnyway)
                    {
                        MessageBox.Show(String.Format("This version is up to date", lastVersionInfo.LatestVersion), "No updates avaible", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                else
                {
                    if (showMessageAnyway)
                        MessageBox.Show("Network error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            });
        }
    }
}
